package com.tedu.notice.service.impl;

import com.tedu.notice.mapper.NoticeMapper;
import com.tedu.notice.pojo.dto.NoticeDto;
import com.tedu.notice.pojo.entity.Notice;
import com.tedu.notice.pojo.vo.NoticeVo;
import com.tedu.notice.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Date;
import java.util.List;

@Transactional
@Service
@Slf4j
public class NoticeServiceImpl implements NoticeService {
    @Autowired
    NoticeMapper NoticeMapper;
    @Override
    public List<NoticeVo> selectNotice(NoticeDto noticeDto) {
        log.debug("开始处理【查询公告信息】的请求，参数={}", noticeDto);
        List<NoticeVo> list = NoticeMapper.selectNotice(noticeDto);
        return list;
    }

    @Override
    public void saveNotice(NoticeDto noticeDto) {
        log.debug("开始处理【保存公告信息】的请求，参数={}", noticeDto);
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeDto, notice);
        if(notice.getId()==null){
            notice.setState("1");
            notice.setCreateTime(new Date());
            NoticeMapper.insert(notice);
            log.debug("保存公告信息成功！");
        }else {
            notice.setUpdateTime(new Date());
            NoticeMapper.update(notice);
            log.debug("修改公告信息成功！");
        }

    }

    @Override
    public void deleteNotice(Integer noticeId) {
        log.debug("开始处理【删除公告信息】的请求，参数={}", noticeId);
        NoticeDto noticeDto = new NoticeDto();
        noticeDto.setId(noticeId);
        List<NoticeVo> list = NoticeMapper.selectNotice(noticeDto);
        if (list != null && !list.isEmpty()) {
            NoticeVo notice = list.get(0);
            // 拼接完整的图片路径, 创建文件对象, 删除磁盘中此路径对应的图片文件
            new File("d:/files" + notice.getNoticePath()).delete();
        } else {
            log.warn("未找到 noticeId={} 对应的公告信息", noticeId);
        }

        NoticeMapper.deleteById(noticeId);
    }

    @Override
    public void updateProperty(NoticeDto noticeDto) {
        log.debug("开始处理【审核公告信息】的请求，参数={}",noticeDto);
        Notice notice = new Notice();
        BeanUtils.copyProperties(noticeDto, notice);
        notice.setUpdateTime(new Date());
        System.out.println(notice.getUpdateTime());
        NoticeMapper.update(notice);
    }
}
